package com.lyt.springboot.util.test;

public class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

class SubtractLinkedLists {
    public static ListNode subtractLists(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, current = dummyHead;

        int borrow = 0;
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int difference = borrow + x - y;
            borrow = difference / 10;

            current.next = new ListNode(difference % 10);
            current = current.next;

            if (p != null) {
                p = p.next;
            }
            if (q != null) {
                q = q.next;
            }
        }

        // 处理最后的借位情况，如果borrow仍然为1，说明最前面需要添加一个-1
        if (borrow > 0) {
            current.next = new ListNode(-borrow);
        }

        // 移除可能的前置0
        ListNode result = dummyHead.next;
        while (result != null && result.val == 0) {
            result = result.next;
        }
        dummyHead.next = result;

        return dummyHead.next;
    }

    public static void printList(ListNode node) {
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // 构建第一个链表 5->3->4->2（表示5342）
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);
        l1.next.next.next = new ListNode(5);

        // 构建第二个链表 9->3->1（表示931）
        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(9);

        ListNode result = subtractLists(l1, l2);
        System.out.println("Subtraction result:");
        printList(result); // 应输出: -402
    }
}